package aoi.movieweb.Controller;

import aoi.movieweb.model.Comment;
import aoi.movieweb.model.Movie;
import aoi.movieweb.service.CommentService;
import aoi.movieweb.service.MovieService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/comment")
public class ControllerComment {

    private final CommentService commentService;
    private final MovieService movieService;


    @Autowired
    public ControllerComment(CommentService commentService, MovieService movieService) {
        this.commentService = commentService;
        this.movieService = movieService;
    }

    // 获取评论
    @GetMapping("/{movieId}")
    public ResponseEntity<List<Comment>> getCommentsByMovieId(@PathVariable Long movieId) {
        List<Comment> comments = commentService.getCommentsByMovieId(movieId);
        return comments.isEmpty() ? ResponseEntity.noContent().build() : ResponseEntity.ok(comments);
    }

    // 添加评论
    @PostMapping
    public ResponseEntity<?> addComment(@Valid @RequestBody Comment comment, BindingResult bindingResult) {
        Long movieId = comment.getMovie().getId();
        // 通过 ID 获取完整的 Movie 对象
        Movie movie = movieService.findById(movieId);
        if (movieId == null) {
            return ResponseEntity.badRequest().body("电影 ID 不能为空");
        }


        if (movie == null) {
            return ResponseEntity.badRequest().body("无效的电影 ID");
        }

        comment.setMovie(movie);

        Comment savedComment = commentService.addComment(comment);
        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body(bindingResult.getFieldErrors());
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(savedComment);
    }

    // 删除评论
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteComment(@PathVariable Long id) {
        commentService.deleteComment(id);
        return ResponseEntity.noContent().build(); // 返回204无内容状态
    }
}

